package com.hh.admin.discount.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;
import org.apache.struts.upload.FormFile;

import com.hh.admin.common.bean.FileRecordBean;
import com.hh.admin.common.service.FileRecordService;
import com.hh.admin.discount.form.UploadFileForm;
import com.hh.common.consts.ConfConst;
import com.hh.common.util.upload.FileUploader;
import com.hh.common.util.upload.RandomFileRenamePolicy;

/**
 * 消费打折
 * 
 * @author Chenem
 * @create 2013-2-27 下午10:27:29
 */
public class UploadFileAction extends MappingDispatchAction {

    private static final Logger log = Logger.getLogger(UploadFileAction.class);

    private static final int MAX_POST_SIZE = 5 * 1024 * 1024;

    private FileRecordService fileRecordService;

    public ActionForward upload(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        UploadFileForm fileForm = (UploadFileForm) form;
        FormFile uploadFile = fileForm.getUpload();
        String fileName = uploadFile.getFileName();
        int fileSize = uploadFile.getFileSize();
        if (fileSize > MAX_POST_SIZE) {
            // throw new Exception(fileName + "文件大小超过限制");
            response.getWriter().print(fileName + "文件大小超过限制");
            return null;
        }

        int endIdx = fileName.lastIndexOf(".");
        if (endIdx == -1) {
            response.getWriter().print("上传文件格式应为 .jpg, .gif, .png");
            return null;
        }

        String end = fileName.substring(endIdx);
        if ((!end.equalsIgnoreCase(".jpg")) && (!end.equalsIgnoreCase(".gif"))
                && (!end.equalsIgnoreCase(".png"))) {
            response.getWriter().print("上传文件格式应为 .jpg, .gif, .png");
            return null;
        }

        RandomFileRenamePolicy rfp = new RandomFileRenamePolicy();
        String newFileName = rfp.rename(fileName);
        String fileUploadDirStr = this.getServlet().getServletContext()
                .getRealPath("/")
                + "resource/uploadimg/share/";
        boolean uploaded = FileUploader.upload(fileUploadDirStr, uploadFile,
                newFileName);
        // response.getWriter().print("success");
        // response.getWriter().print(fileUploadDirStr + newFileName);

        if (!uploaded) {
            response.getWriter().print("error");
            System.out.println("上传文件[" + fileName + "]到目录[" + fileUploadDirStr
                    + "]失败");
            throw new Exception("上传文件[" + fileName + "]到目录[" + fileUploadDirStr
                    + "]失败");
        }

        // 文件上传成功，记录文件上传到数据库中
        FileRecordBean param = new FileRecordBean();
        param.setFileName(fileName);
        param.setFilePath("resource/uploadimg/share/" + newFileName);
        int id = fileRecordService.insertFileRecord(param);
        log.debug("[upload] 文件上传：FileRecordBean=[" + param + "] 结果id=[" + id
                + "]");

        String callback = request.getParameter("CKEditorFuncNum");

        response.getWriter().println("<script type=\"text/javascript\">");
        response.getWriter().println(
                "window.parent.CKEDITOR.tools.callFunction(" + callback + ",'"
                        + ConfConst.WEB_URL + "/resource/uploadimg/share/" + newFileName
                        + "','')");
        response.getWriter().println("</script>");

        return null;
    }

    public void setFileRecordService(FileRecordService fileRecordService) {
        this.fileRecordService = fileRecordService;
    }

}
